package com.order.manager.controller.Order;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.order.manager.Model.*;
import com.order.manager.Model.other.MenuCount;
import com.order.manager.Model.other.OrderCreationRequest;
import com.order.manager.Model.other.OrderView;
import com.order.manager.Model.other.RestBean;
import com.order.manager.service.impl.*;
import com.order.manager.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    OrderInfoServiceImpl orderInfoService;

    @Resource
    ShopInfoServiceImpl shopInfoService;

    @Resource
    MenuInfoServiceImpl menuInfoService;


    @Resource
    UserInfoServiceImpl userInfoService;

    @Resource
    SenderInfoServiceImpl senderInfoService;

    @Resource
    EvaluateInfoServiceImpl evaluateInfoService;

    @Resource
    UserAddressServiceImpl userAddressService;

    @Resource
    OrderSendInfoServiceImpl orderSendInfoService;

    @Resource
    JwtUtil jwtUtil;

    @Resource
    OrderMenuInfoServiceImpl orderMenuInfoService;


    @RequestMapping("/create")
    public RestBean createOrder(@RequestBody OrderCreationRequest request, HttpServletRequest httpServletRequest) {
        OrderInfo orderInfo = request.getOrderInfo();
        List<OrderMenuInfo> menuInfos = request.getMenuInfos();
        if (menuInfos.isEmpty()) return RestBean.failure(403, "菜单不能为空");
        String uuid = jwtUtil.getJwtUsername(httpServletRequest);
        String orderId = UUID.randomUUID().toString();
        orderInfo.setOrderId(orderId);
        orderInfo.setUserId(uuid);
        orderInfo.setInputTime(new Date());
        orderInfo.setApplyState(0);
        if (orderInfo.getType() == 2) {
            //1堂食，2外卖
            orderInfo.setMoney(BigDecimal.valueOf(2));
        } else {
            orderInfo.setMoney(BigDecimal.valueOf(0));
        }
        for (OrderMenuInfo menu : menuInfos) {
            menu.setOrderId(orderId);
            menu.setInputTime(new Date()); // Using Instant for current time
            MenuInfo menuInfo = menuInfoService.getById(menu.getMenuId());
            if (menuInfo != null && menuInfo.getMenuPrice() != null) {
                BigDecimal menuPrice = new BigDecimal(menuInfo.getMenuPrice().toString());
                BigDecimal itemCost = menuPrice.multiply(BigDecimal.valueOf(menu.getCount()));
                orderInfo.setMoney(orderInfo.getMoney().add(itemCost)); // Using BigDecimal add method
            }
            orderMenuInfoService.save(menu);
        }
        return orderInfoService.save(orderInfo) ? RestBean.success(orderInfo) : RestBean.failure(500, "订单创建失败");
    }

    @RequestMapping("/query")
    public RestBean queryOrder(HttpServletRequest request) {
        String uuid = jwtUtil.getJwtUsername(request);
        List<OrderInfo> orderInfos = orderInfoService.list(new QueryWrapper<OrderInfo>()
                .eq("user_id", uuid).orderByDesc("input_time"));
        List<OrderView> orderViews = new ArrayList<>();
        for (OrderInfo order : orderInfos) {
            OrderView orderView = createOrderView(order);
            orderViews.add(orderView);
        }
        return RestBean.success(orderViews);
    }

    @RequestMapping("/view/{id}")
    public RestBean viewSomeone(@PathVariable String id) {
        OrderInfo order = orderInfoService.getById(id);
        if (order == null) return RestBean.failure(403, "不存在该订单信息");
        OrderView orderView = createOrderView(order);
        return RestBean.success(orderView);
    }

    //订单支付
    @RequestMapping("/apply/{orderId}")
    public RestBean applyOrder(@PathVariable String orderId, HttpServletRequest request) {
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        String uuid = jwtUtil.getJwtUsername(request);
        UserInfo userInfo = userInfoService.getById(uuid);
        BigDecimal userMoney = BigDecimal.valueOf(Double.parseDouble(userInfo.getMoney()));
        if (userMoney.compareTo(orderInfo.getMoney()) < 0) {
            return RestBean.failure(403, "余额不足");
        }
        userInfo.setMoney(userMoney.subtract(orderInfo.getMoney()).toString());
        userInfoService.updateById(userInfo);
        orderInfo.setApplyState(1);
        return orderInfoService.updateById(orderInfo) ? RestBean.success(orderInfo) : RestBean.failure(403, "支付失败");
    }

    @RequestMapping("/orderForShop/{page}/{item}")
    public RestBean orderForShop(@PathVariable int page,@PathVariable int item,HttpServletRequest request){
        String uuid = jwtUtil.getJwtUsername(request);
        ShopInfo shopMasterId = shopInfoService.getOne(new QueryWrapper<ShopInfo>()
                .eq("shop_master_id", uuid)
        );
        if (shopMasterId == null)
            return RestBean.failure(403,"店铺信息异常");
        return RestBean.success(orderInfoService.queryByShop(page,item,shopMasterId.getShopId()));
    }

    //订单退款
    @RequestMapping("/refund/{orderId}")
    public RestBean refundOrder(@PathVariable String orderId) {
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null) return RestBean.failure(403, "不存在该订单信息");
        if (orderInfo.getApplyState() == 0) return RestBean.failure(403, "该订单还未付款");
        if (orderInfo.getApplyState() == 2) return RestBean.failure(403, "该订单已评价，不予退款");
        orderInfo.setApplyState(-1);
        UserInfo userInfo = userInfoService.getById(orderInfo.getUserId());
        userInfo.setMoney(BigDecimal.valueOf(Double.parseDouble(userInfo.getMoney())).add(orderInfo.getMoney()).toString());
        if (orderInfoService.updateById(orderInfo) && userInfoService.updateById(userInfo)) {
            return RestBean.success(orderInfo);
        }
        return RestBean.failure(500, "退款失败");
    }

    //订单创建
    private OrderView createOrderView(OrderInfo order) {
        OrderView orderView = new OrderView();
        orderView.setOrderId(order.getOrderId());
        orderView.setMoney(order.getMoney());
        if (userAddressService.count(new QueryWrapper<UserAddress>().eq("address_id", order.getAddressId())) != 0) {
            orderView.setAddress(userAddressService.getById(order.getAddressId()).getAddress());
        } else {
            orderView.setAddress("未知");
        }
        orderView.setDemo(order.getDemo());
        orderView.setShopName(shopInfoService.getById(order.getShopId()).getShopName());
        orderView.setType(order.getType());
        orderView.setApplyState(order.getApplyState());
        orderView.setInputDate(order.getInputTime());
        List<OrderMenuInfo> orderMenuInfos = orderMenuInfoService.list(new QueryWrapper<OrderMenuInfo>().eq("order_id", order.getOrderId()));
        List<MenuCount> menuCounts = new ArrayList<>();
        for (OrderMenuInfo orderMenuInfo : orderMenuInfos) {
            MenuCount menuCount = new MenuCount();
            menuCount.setCount(orderMenuInfo.getCount());
            MenuInfo menuInfo = menuInfoService.getById(orderMenuInfo.getMenuId());
            menuCount.setMenuPrice(menuInfo.getMenuPrice());
            menuCount.setMenuName(menuInfo.getMenuName());
            menuCount.setMenuPicture(menuInfo.getMenuPicture());
            menuCount.setMenuId(orderMenuInfo.getMenuId());
            menuCount.setCount(orderMenuInfo.getCount());
            menuCounts.add(menuCount);
        }
        orderView.setMenuCounts(menuCounts);
        OrderSendInfo orderSendInfo = orderSendInfoService.
                getOne(new QueryWrapper<OrderSendInfo>().eq("order_id", order.getOrderId()));
        if (orderSendInfo != null) {
            orderView.setSendState(orderSendInfo.getState() == 0 ? "正在配送" :
                    orderSendInfo.getState() == 1 ? "已送达" :
                            orderSendInfo.getState() == -1 ? "骑手已退单，待其他骑手接单" : "未知");
            orderView.setSenderName(JSON.toJSONString(userInfoService.getById(senderInfoService.getById(orderSendInfo.getSenderId())).getUsername()));
        }
        return orderView;
    }


}
